package com.carefree.common.exception;

import com.carefree.common.core.Result;
import com.carefree.common.emus.StatusCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName:GlobalExceptionHandler
 * @Description: 全局异常处理 （发生异常时，首先查找是否有已指定的异常处理，有就执行、没有就执行兜底的异常处理）
 * @Author Tengbin tengbin234@163.com
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return Result.error(StatusCodeEnum.FAUIL.getCode(), StatusCodeEnum.FAUIL.getMessage());
    }

    /**
     * 运行时异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return Result.error(StatusCodeEnum.DATA_ERROR.getCode(), StatusCodeEnum.DATA_ERROR.getMessage());
    }


    /**
     * 异常处理-兜底
     *
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public Result<?> throwableHandle(Throwable throwable) {
        log.error("throwable", throwable);
        return Result.error(StatusCodeEnum.INTERNAL_SERVER_ERROR.getCode(), StatusCodeEnum.INTERNAL_SERVER_ERROR.getMessage());
    }

}
